//
//  PlayController.m
//  Travel_M_Travel
//
//  Created by dlios on 15-3-28.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "PlayController.h"
#import "STKAudioPlayer.h"
#import "SampleQueueId.h"
#import "UIImageView+WebCache.h"
#import "EFCircularSlider.h"
#import "PlayCell.h"
#import "NetworkingHandler.h"
#import "Play.h"
#import "ASValueTrackingSlider.h"

@interface PlayController ()<STKAudioPlayerDelegate, UITableViewDataSource, UITableViewDelegate, ASValueTrackingSliderDelegate, ASValueTrackingSliderDataSource>
@property (nonatomic, strong) STKAudioPlayer *player;

@property (retain, nonatomic) EFCircularSlider *processSlider;
@property (retain, nonatomic) UILabel *timeLabel;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *headerView;
@property (nonatomic, retain) UIImageView *largeImg;
@property (nonatomic, retain) UIButton *playBTN;
@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, retain) NSURL *url;
@property (nonatomic, retain) PlayCell *cell;
@property (nonatomic, retain) ASValueTrackingSlider *playProgress;

- (void)beginAction:(id)sender;
- (void)seekSlider:(id)sender;
- (void)stopAction:(id)sender;
- (void)pauseAction:(id)sender;
- (void)volumeSlider:(id)sender;
- (void)muteSwich:(id)sender;
@end

@implementation PlayController

+ (instancetype)shareInstance
{
    static PlayController *play = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        play = [[PlayController alloc] init];
    });
    return play;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    // 简介tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    // headerView
    self.headerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.tableView.frame.size.width, self.view.frame.size.height*3/5)];
    self.tableView.tableHeaderView = _headerView;
    [_headerView release];
    
    // headerView上方图片
    self.largeImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.headerView.frame.size.width, self.headerView.frame.size.height*3/4)] ;
    self.largeImg.userInteractionEnabled = YES;
    [self.headerView addSubview:self.largeImg];
    [_largeImg release];
    // 返回按钮
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(5, 15, 28, 28);
    [back setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.largeImg addSubview:back];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, self.headerView.frame.size.height*3/4, self.largeImg.frame.size.width, self.headerView.frame.size.height/4)];
    //    view.alpha = 0.5;
    [self.headerView addSubview:view];
    [view release];
    
    // 播放按钮
    self.playBTN = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_playBTN setFrame:CGRectMake(80, 8, 40, 40)];
    [_playBTN setBackgroundImage:[[UIImage imageNamed:@"playGray.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [_playBTN addTarget:self action:@selector(beginAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_playBTN];
    
    // 停止按钮
    UIButton *stop = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [stop setFrame:CGRectMake(135, 15, 25, 25)];
    //    [stop setBackgroundColor:[UIColor redColor]];
    [stop setBackgroundImage:[[UIImage imageNamed:@"stop.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [stop addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:stop];
    // 下一首
    UIButton *next = [UIButton buttonWithType:UIButtonTypeSystem];
    [next setFrame:CGRectMake(170, 15, 25, 25)];
    [next setBackgroundImage:[UIImage imageNamed:@"next.png"] forState:UIControlStateNormal];
    [next addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:next];
    // 上一首
    UIButton *last = [UIButton buttonWithType:UIButtonTypeSystem];
    [last setFrame:CGRectMake(40, 15, 25, 25)];
    [last setBackgroundImage:[UIImage imageNamed:@"last.png"] forState:UIControlStateNormal];
    [last addTarget:self action:@selector(last:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:last];
    // 音量
    UISlider *volumeSlider = [[UISlider alloc] initWithFrame:CGRectMake(210, 15, 105, 20)];
    //    [volumeSlider setBackgroundColor:[UIColor orangeColor]];
    [volumeSlider setMaximumValue:10.0f];
    [volumeSlider setMinimumValue:0.0f];
    [volumeSlider setValue:5.0f];
    [volumeSlider setMinimumValueImage:[UIImage imageNamed:@"vMin.png"]];
    [volumeSlider setMaximumValueImage:[UIImage imageNamed:@"vMax.png"]];
    //    [volumeSlider setMinimumTrackImage:[UIImage imageNamed:@"vMin.png"] forState:UIControlStateNormal];
    //    [volumeSlider setMaximumTrackImage:[UIImage imageNamed:@"vMax.png"] forState:UIControlStateNormal];
    [volumeSlider addTarget:self action:@selector(volumeSlider:) forControlEvents:UIControlEventValueChanged];
    [view addSubview:volumeSlider];
    // 时间进度
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(225, 35  , 100, 20)];
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    self.timeLabel.text = @"00.00/00.00";
    [view addSubview:_timeLabel];
    [_timeLabel release];
    
    //    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    //    self.player.delegate = self;
    //    self.player.volume = 0.2;
    //    self.player.meteringEnabled = YES;
    //    self.player.volume = 1;
    //
    // 播放器
    self.player = [STKAudioPlayer sharedInstance];
    
    // 进度条
    self.playProgress = [[ASValueTrackingSlider alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 30)];
    self.playProgress.dataSource = self;
    self.playProgress.minimumValue = 0;
    self.playProgress.maximumValue = 100;
    [self.playProgress setPopUpViewCornerRadius:8];
    self.playProgress.font = [UIFont fontWithName:@"HelveticaNeue-CondensedBlack" size:26];
    [self.playProgress addTarget:self action:@selector(seekSlider:) forControlEvents:UIControlEventValueChanged];
    self.playProgress.textColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    
    UIColor *coldBlue = [UIColor colorWithHue:0.6 saturation:0.7 brightness:1.0 alpha:1.0];
    UIColor *blue = [UIColor colorWithHue:0.55 saturation:0.75 brightness:1.0 alpha:1.0];
    UIColor *green = [UIColor colorWithHue:0.3 saturation:0.65 brightness:0.8 alpha:1.0];
    UIColor *yellow = [UIColor colorWithHue:0.15 saturation:0.9 brightness:0.9 alpha:1.0];
    UIColor *red = [UIColor colorWithHue:0.0 saturation:0.8 brightness:1.0 alpha:1.0];
    
    [self.playProgress setPopUpViewAnimatedColors:@[coldBlue, blue, green, yellow, red]
                                    withPositions:@[@0, @25, @50, @75, @100]];
    [view addSubview:self.playProgress];
    [_playProgress release];
    
    //    self.processSlider = [[EFCircularSlider alloc] initWithFrame:CGRectMake(200, 180, 80, 80)];
    //    [_processSlider addTarget:self action:@selector(seekSlider:) forControlEvents:UIControlEventValueChanged];
    //    [self.largeImg addSubview:_processSlider];
    //    [_processSlider release];
    
    
    
    //    UISwitch *switch1 = [[UISwitch alloc] initWithFrame:CGRectMake(100, 20, 15, 6)];
    //    [switch1 addTarget:self action:@selector(muteSwich:) forControlEvents:UIControlEventValueChanged];
    //    switch1.on = YES;
    //    [self.largeImg addSubview:switch1];
    //    [switch1 release];
    
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", self.track.trackId];
    
    [NetworkingHandler requestWithUrl:str completion:^(NSDictionary *resultDic) {
        
        self.play = [[Play alloc] initWithDic:resultDic];
        //        NSLog(@"self.play!~~~~~!: %@", self.play);
        
        [_tableView reloadData];
    }];
    
    
}

// 解决viewdidappear无法播放上下首的问题
- (void)setTrack:(Tracks *)track
{
    if (_track != track) {
        [_track release];
        _track = [track retain];
    }
    if (track.localUrl.length == 0) {
        self.url = [NSURL URLWithString:self.track.playUrl32];
    } else {
        self.url = [NSURL URLWithString:self.track.localUrl];
    }
    
    STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:_url];
    
    [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:_url andCount:0]];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track1) userInfo:nil repeats:YES];
    
    [self.playBTN setBackgroundImage:[UIImage imageNamed:@"pauseGray.png"] forState:UIControlStateNormal];
}

- (void)setPlay:(Play *)play
{
    if (_play != play) {
        [_play release];
        _play = [play retain];
    }
    
    //    [self netWork];
    //    _cell.play = self.play;
}

#pragma mark netWork请求
- (void)netWork
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%@", self.track.trackId];
    [NetworkingHandler requestWithUrl:str completion:^(NSDictionary *resultDic) {
        
        NSLog(@"self.play!~~~~~!: %@", resultDic);
        _play = [[Play alloc] initWithDic:resultDic];
        
        [_tableView reloadData];
    }];
}

// 因为单例每次都进入同样的页面, 在试图将要出现的方法里实现为视图重新赋值, 并且实现点击第一次进入播放页面直接播放音乐
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    NSString *strImg = self.track.coverLarge;
    NSURL *urlImg = [NSURL URLWithString:strImg];
    [self.largeImg setImageWithURL:urlImg];
    
    self.url = [NSURL URLWithString:self.track.playUrl32];
    STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:_url];
    
    [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:_url andCount:0]];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track1) userInfo:nil repeats:YES];
    
    [self.playBTN setBackgroundImage:[UIImage imageNamed:@"pauseGray.png"] forState:UIControlStateNormal];
    
    
    [self netWork];
    
    //    _cell.play = self.play;
    [self.tableView reloadData];
}

- (NSString *)slider:(ASValueTrackingSlider *)slider stringForValue:(float)value
{
    NSInteger proMin = (NSInteger)self.player.progress / 60;
    NSInteger proSec = (NSInteger)self.player.progress % 60;
    
    NSInteger durMin = (NSInteger)self.player.duration / 60;
    NSInteger durSec = (NSInteger)self.player.duration % 60;
    
    NSString *s = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    return s;
}

////实现点击cell进入播放页面直接播放音乐   bug: 无法播放上一首或下一首
//- (void)viewDidAppear:(BOOL)animated
//{
//    self.url = [NSURL URLWithString:self.track.playUrl32];
//
//    STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:_url];
//
//    [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:_url andCount:0]];
//
//    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track1) userInfo:nil repeats:YES];
//
//    [self.play setBackgroundImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    self.cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (_cell == nil) {
        _cell = [[[PlayCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
    }
    
    //        _cell.albumTitle.text = self.play.title;
    //        _cell.categoryName.text = self.play.categoryName;
    //        _cell.tags.text = self.play.tags;
    //        _cell.richIntro.text = self.play.richIntro;
    //        _cell.lyric.text = self.play.lyric;
    
    _cell.play = self.play;
    return _cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    PlayCell *cell = (PlayCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return 300;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)next:(UIButton *)next
{
    self.track = [self.arr objectAtIndex:self.row += 1];
    NSString *strImg = self.track.coverLarge;
    NSURL *urlImg = [NSURL URLWithString:strImg];
    [self.largeImg setImageWithURL:urlImg];
    [_player setState:STKAudioPlayerStateReady];
    [self beginAction:nil];
}

- (void)last:(UIButton *)last
{
    self.track = [self.arr objectAtIndex:self.row -= 1];
    NSString *strImg = self.track.coverLarge;
    NSURL *urlImg = [NSURL URLWithString:strImg];
    [self.largeImg setImageWithURL:urlImg];
    [_player setState:STKAudioPlayerStateReady];
    [self beginAction:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  点击播放音乐, 生成一个播放数据源, 添加到播放器中
 *
 */
- (void)beginAction:(UIButton *)sender {
    
    //    NSLog(@"~~~%d", sender.selected);
    if (_player.state == STKAudioPlayerStateReady) {
        
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:_url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:_url andCount:0]];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track1) userInfo:nil repeats:YES];
        
        [self.playBTN setBackgroundImage:[UIImage imageNamed:@"pauseGray.png"] forState:UIControlStateNormal];
    }
    if (_player.state == STKAudioPlayerStatePlaying){
        [self.playBTN setBackgroundImage:[UIImage imageNamed:@"playGray.png"] forState:UIControlStateNormal];
        [_player pause];
    } else if (_player.state == STKAudioPlayerStatePaused) {
        [self.playBTN setBackgroundImage:[UIImage imageNamed:@"pauseGray.png"] forState:UIControlStateNormal];
        [_player resume];
        
    }
    if (_player.state == STKAudioPlayerStateStopped) {
        
        
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:_url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:_url andCount:0]];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track1) userInfo:nil repeats:YES];
        [self.playBTN setBackgroundImage:[UIImage imageNamed:@"pauseGray.png"] forState:UIControlStateNormal];
    }
}



/**
 *  每秒更新slider和label显示时间, timer方法
 */
- (void)track1
{
    if (_playProgress) {
        _playProgress.maximumValue = self.player.duration;
        _playProgress.value = self.player.progress;
        
        
        NSInteger proMin = (NSInteger)self.player.progress / 60;
        NSInteger proSec = (NSInteger)self.player.progress % 60;
        
        NSInteger durMin = (NSInteger)self.player.duration / 60;
        NSInteger durSec = (NSInteger)self.player.duration % 60;
        
        _timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    }
}
//- (void)progressSlider:(EFCircularSlider *)slider{
//
//    if (slider) {
//        slider.maximumValue = self.player.duration;
//        slider.currentValue = self.player.progress;
//
//        NSInteger proMin = (NSInteger)self.player.progress / 60;
//        NSInteger proSec = (NSInteger)self.player.progress % 60;
//
//        NSInteger durMin = (NSInteger)self.player.duration / 60;
//        NSInteger durSec = (NSInteger)self.player.duration % 60;
//
//        _timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
//    }
//        _valueLabel.text = [NSString stringWithFormat:@"%.02f", slider.currentValue];
//}

/**
 *  进度条的方法, 改变播放器的播放进度
 *
 *  @param sender slider参数
 */
- (void)seekSlider:(ASValueTrackingSlider *)slider {
    
    if (_player) {
        //         _valueLabel.text = [NSString stringWithFormat:@"%.02f", slider.value];
        [self.player seekToTime:slider.value];
    }
}

// 停止播放
- (void)stopAction:(id)sender {
    [self.playBTN setBackgroundImage:[UIImage imageNamed:@"playGray"] forState:UIControlStateNormal];
    [_player stop];
}

// 暂停按钮
//- (void)pauseAction:(id)sender {
//
//    NSLog(@"%d", _player.state);
//    UIButton *button = sender;
//    if (_player.state == STKAudioPlayerStatePaused) {
//        [button setTitle:@"pause" forState:UIControlStateNormal];
//        [_player resume];
//    } else if (_player.state == STKAudioPlayerStatePlaying) {
//        [button setTitle:@"resume" forState:UIControlStateNormal];
//        [_player pause];
//    } else if (_player.state == STKAudioPlayerStateReady) {
//        [button setTitle:@"pause" forState:UIControlStateNormal];
//
//        [self beginAction:nil];
//    }
//}

// 音量按钮
- (void)volumeSlider:(id)sender {
    UISlider *slider = sender;
    NSLog(@"%f", slider.value);
    [_player setVolume:slider.value];
}



// 静音
- (void)muteSwich:(id)sender {
    
    _player.muted = ![(UISwitch *)sender isOn];
}


#pragma mark - 播放器协议方法
/// Raised when an item has started playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"播放状态改变");
}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(@"结束原因: %d, progress: %f, duration: %f", stopReason, progress, duration);
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{
    NSLog(@"信息: %@", line);
}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{
    NSLog(@"未知");
}




@end
